package org.springblade.modules.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.base.Strings;
import lombok.AllArgsConstructor;
import org.springblade.common.tool.UploadFileTest;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.launch.props.BladeProperties;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.log.publish.WebApiLogPublisher;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.app.entity.*;
import org.springblade.modules.app.service.*;
import org.springblade.modules.app.vo.AppAreaVO;
import org.springblade.modules.desk.service.INoticeService;
import org.springblade.modules.desk.vo.NoticeVO;
import org.springblade.modules.desk.wrapper.NoticeWrapper;
import org.springblade.modules.util.PoiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created by admin on 2019/4/8.
 */
@Controller
@RequestMapping("/web")
@AllArgsConstructor
public class IndexController extends BladeController {
	@Autowired
	private IAppUserService appUserService;

	@Autowired
	private IAppAnimalService appAnimalService;

	@Autowired
	private IAppPlantService appPlantService;

	@Autowired
	private INoticeService noticeService;
	@Autowired
	private IUserNoticeService userNoticeService;

	@Autowired
	private IAppAreaService areaService;
	@Autowired
	private IAppAreaPlaceService placeService;
	@Autowired
	BladeProperties bladeProperties;

	IAppExcelService excelService;

	@RequestMapping("/excel")
	@ResponseBody
	public R<List<AppExcel>> excel() {
		List<AppExcel> appExcels = excelService.list();
		return R.data(appExcels);
	}

	@GetMapping("/im")
	public void importExcel() throws RuntimeException {
		PoiUtil.readExcel("C:\\Users\\admin\\Desktop\\b.xls", excelService);
	}


	@RequestMapping("/saveLogin")
	public String saveLogin(Model model, String name, String password, Boolean remember,
							HttpServletRequest request, HttpServletResponse response) {
		System.out.println("remember:" + remember);
		String message = "";
		if (request.getSession().getAttribute("user") == null) {
			model.addAttribute("name", name == null ? "" : name);
			model.addAttribute("password", password == null ? "" : name);
			if (Func.isAnyBlank(name, password)) {
				message = "账号密码不能为空";
				model.addAttribute("msg", message);
				return "login.html";
			}
			AppUser appUser = appUserService.getBaseMapper().selectOne(Wrappers.<AppUser>query().lambda().eq(AppUser::getAccount, name).eq(AppUser::getPassword, password));
			if (appUser == null) {
				message = "账户密码错误";
				model.addAttribute("msg", message);
				//记录日志
				WebApiLogPublisher.publishEvent("saveLogin", "org.springblade.modules.web.IndexController", "登录失败", 0);
				return "login.html";
			}

			if (appUser.getStatus() == 2) {
				message = "用户被禁用";
				model.addAttribute("msg", message);
				//记录日志
				WebApiLogPublisher.publishEvent("saveLogin", "org.springblade.modules.web.IndexController", "用户被禁用", 0);
				return "login.html";
			}

			request.getSession().setAttribute("userId", appUser.getId());
			request.getSession().setAttribute("user", appUser);
			request.setAttribute("user", appUser);
			request.setAttribute("name", appUser.getNickName());
			//记录日志
			WebApiLogPublisher.publishEvent("saveLogin", "org.springblade.modules.web.IndexController", "登录成功", 0);
			//写cookies
			if (remember != null) {
				appUserService.readCookie(UUID.randomUUID().toString(), response, request);
			} else {
			}
		}
		String path = (String) request.getSession().getAttribute("path");
		if (Func.isNotBlank(path) && !path.contains("login")) {
			request.getSession().setAttribute("path", null);
			try {
				response.sendRedirect(path);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {

			return "index.html";
		} catch (Exception e) {
			e.printStackTrace();
		}
		//	System.out.println("user:" + request.getAttribute("user"));
		return "";
	}

	@ApiLog("首页")
	@RequestMapping("/index")
	public String index() {
		System.out.println("hello");
		return "index.html";
	}

	@GetMapping("/login")
	public String login() {
		return "login.html";
	}

	@ApiLog("退出账号")
	@GetMapping("/unlogin")
	public String unLogin(HttpServletRequest request) {
		request.getSession().setAttribute("user", null);
		request.setAttribute("user", null);
		return "login.html";
	}

	@GetMapping("/{category}")
	public String index(@RequestParam Map<String, Object> all, Query query,
						@PathVariable Integer category, Model model) {
		query.setSize(4);
		model.addAttribute("category", category);
		for (Map.Entry<String, Object> entry : all.entrySet()) {
			model.addAttribute(entry.getKey(), entry.getValue());
		}
		if (category == 1) {
			this.animal(all, query, model);
		} else {
			this.plant(all, query, model);
		}
		return "wild_animal.html";
	}

	@GetMapping("/animal")
	@ApiLog("搜索动物")
	public String animal(@RequestParam Map<String, Object> all, Query query,
						 Model model) {
		query.setSize(4);
		model.addAttribute("category", 1);
		for (Map.Entry<String, Object> entry : all.entrySet()) {
			model.addAttribute(entry.getKey(), entry.getValue());
		}
		QueryWrapper<AppAnimal> queryWrapper = Condition.getQueryWrapper(all, AppAnimal.class);
		IPage<AppAnimal> animalPage = appAnimalService.page(Condition.getPage(query), queryWrapper);
		model.addAttribute("animal", animalPage);
		return "wild_animal.html";
	}

	@ApiLog("搜索植物")
	@GetMapping("/plant")
	public String plant(@RequestParam Map<String, Object> all, Query query,
						Model model) {
		query.setSize(4);
		model.addAttribute("category", 2);
		for (Map.Entry<String, Object> entry : all.entrySet()) {
			model.addAttribute(entry.getKey(), entry.getValue());
		}
		QueryWrapper<AppPlant> queryWrapper = Condition.getQueryWrapper(all, AppPlant.class);
		IPage<AppPlant> palntAnimal = appPlantService.page(Condition.getPage(query), queryWrapper);
		model.addAttribute("animal", palntAnimal);
		return "wild_animal.html";
	}

	@GetMapping("/info")
	public String info(HttpServletRequest request) {
		this.getUser(request);
		return "mydata.html";
	}

	@ApiLog("修改个人资料")
	@GetMapping("/saveInfo")
	public String saveInfo(AppUser u, HttpServletRequest request) {
		appUserService.saveOrUpdate(u);
		this.getUser(request);
		return "mydata.html";
	}

	@GetMapping("/rest")
	public String restPassword(String oldPassword, String passowrd, HttpServletRequest request, Model mm) {
		String msg = "";
		AppUser user = (AppUser) request.getSession().getAttribute("user");
		if (Func.isNotBlank(oldPassword)) {
			if (user.getPassword().equals(oldPassword)) {
				user.setPassword(passowrd);
				boolean f = appUserService.saveOrUpdate(user);
				if (f) {
					WebApiLogPublisher.publishEvent("restPassword", "org.springblade.modules.web.IndexController", "修改密码成功", 0);
					msg = "修改成功";
				} else {
					msg = "修改失败";
				}
			} else {
				msg = "密码错误";
			}
			WebApiLogPublisher.publishEvent("restPassword", "org.springblade.modules.web.IndexController", "修改密码错误", 0);
		}
		mm.addAttribute("msg", msg);
		this.getUser(request);
		return "change_password.html";
	}

	@GetMapping("/desc")
	public String infoDesc(HttpServletRequest request, Model model, String ids) {
		AppUser user = this.getUser(request);
		if (Func.isNotBlank(ids)) {
			List<UserNotice> list = new ArrayList<>();
			Arrays.asList(ids.split(",")).forEach(id -> {
					UserNotice userNotice = new UserNotice();
					userNotice.setNoticeId(Func.toInt(id));
					userNotice.setUserId(user.getId());
					list.add(userNotice);
				}
			);
			userNoticeService.saveBatch(list);
		}
		List<NoticeVO> noticeList = noticeService.selectUserNotice(user.getId());
		NoticeWrapper noticeWrapper = new NoticeWrapper(null);
		model.addAttribute("list", noticeWrapper.listNodeVO(noticeList));
		return "information.html";
	}

	@GetMapping("/desc/{id}")
	public String information_details(HttpServletRequest request, @PathVariable Integer id, Model model) {
		NoticeVO notice = noticeService.selectOneNotice(id);
		List list = new ArrayList<>();
		list.add(notice);
		NoticeWrapper noticeWrapper = new NoticeWrapper(null);
		model.addAttribute("info", noticeWrapper.listNodeVO(list).get(0));
		return "information_details.html";
	}
//
//	@GetMapping("/driver")
//	public String driver(Model model) {
//		Object param = appAnimalService.selectOne();
//		model.addAttribute("param", param);
//		model.addAttribute("param1", appAnimalService.selectCagegory());
//		model.addAttribute("animal", appAnimalService.listMaps());
//		model.addAttribute("palnt", appPlantService.listMaps());
//		model.addAttribute("n1", noticeService.list(Wrappers.<Notice>query().lambda().eq(Notice::getCategory, 1)));
//		model.addAttribute("n2", noticeService.list(Wrappers.<Notice>query().lambda().eq(Notice::getCategory, 2)));
//		return "cockpit.html";
//	}

	@GetMapping("/driver")
	public String driver(Model model) {
		return "cockpit1.html";
	}

	@GetMapping("/plan")
	public String plan(Model model) {
		return "planimetering.html";
	}

	@GetMapping("/result")
	@ResponseBody
	public R result(String path, String height,
					String pixel, String angle1, String angle2,
					String no, String focus, HttpServletRequest request) {
		AppArea appArea = new AppArea();
		appArea.setHeight(height);
		appArea.setPixel(pixel);
		appArea.setAngle1(angle1);
		appArea.setAngle2(angle2);
		appArea.setNo(no);
		appArea.setImgs(path);
		appArea.setFocus(focus);
		appArea.setCreateDate(LocalDateTime.now());
		appArea.setUpdateDate(LocalDateTime.now());
		AppUser appUser = this.getUser(request);
		appArea.setUserId(appUser.getId());
		appArea.setUserName(appUser.getNickName());
		appArea.setAccount(appUser.getAccount());
		String result = "0";
		try {
			//	result = String.valueOf(Math.random() * 1000);
			result = resultArea(path.replaceAll("http.*?/images",
				String.valueOf(bladeProperties.getProp().get("remote-path"))),
				height, pixel, angle1, focus);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail("计算接口错误");
		}
		appArea.setResult(result);
		boolean f = areaService.save(appArea);
		if (!f) {
			return R.fail("保存失败");
		}
		Map param = new HashMap();
		param.put("result", result);
		param.put("id", appArea.getId());
		return R.data(param);

	}

	@GetMapping("/position")
	@ResponseBody
	public R position(String position, String no, Integer id) throws Exception {
		if (!Strings.isNullOrEmpty(position) && !Strings.isNullOrEmpty(no) && id != null) {
			List<AppAreaPlace> places = new ArrayList<>();
			List<List> mapList = (List) JSON.parse(position);
			mapList.forEach(map -> {
				AppAreaPlace appAreaPlace = new AppAreaPlace();
				String lat = String.valueOf(map.get(0));
				String lng = String.valueOf(map.get(1));
				appAreaPlace.setLat(lat);
				appAreaPlace.setLnt(lng);
				appAreaPlace.setNo(no);
				appAreaPlace.setAreaId(id);
				places.add(appAreaPlace);
			});
			placeService.saveBatch(places);
		}
		return R.status(true);
	}

	@GetMapping("/history")
	@ResponseBody
	public R formDate(String no) {
		List<AppAreaVO> appAreaVOList = areaService.selectAreaVo(no);
		Map param = new HashMap();
		param.put("list", appAreaVOList);
		return R.data(param);
	}

	@GetMapping("/cal")
	public String calculate(Integer id, Model model) {
		AppArea appArea = areaService.getById(id);
		List<AppAreaPlace> appAreaPlaceList = placeService.list(Wrappers.<AppAreaPlace>query().lambda().eq(AppAreaPlace::getAreaId, appArea.getId()));
		model.addAttribute("area", appArea);
		model.addAttribute("list", appAreaPlaceList);
		return "calculate_details.html";
	}

	@RequestMapping("/gps")
	public String gis_map() {
		return "gis_map.html";
	}

	private AppUser getUser(HttpServletRequest request) {
		//获取最新的用户信息
		AppUser user = (AppUser) request.getSession().getAttribute("user");
		request.getSession().setAttribute("user", appUserService.getById(user.getId()));
		return user;
	}

	public static String resultArea(String filePath, String dis, String pixle, String xiangjiao, String f) throws Exception {
		String res = UploadFileTest.upload(filePath, "http://127.0.0.1:82/paogongdi/build/build", dis, pixle, xiangjiao, f);
		return res;
	}

}
